from rest_framework import status, generics, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.utils import timezone
from .serializers import (
    UserRegisterSerializer, UserLoginSerializer, UserSerializer,
    MembershipTypeSerializer, LoginLogSerializer, ChangePasswordSerializer
)
from .models import User, MembershipType, LoginLog


class CheckEmailView(APIView):
    """检查邮箱是否已存在"""
    permission_classes = [permissions.AllowAny]
    
    def post(self, request):
        email = request.data.get('email')
        if not email:
            return Response(
                {'error': '邮箱地址不能为空'}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        exists = User.objects.filter(email=email).exists()
        return Response({
            'exists': exists,
            'message': '该邮箱已经注册过了，你可以直接登录或者换一个邮箱账号注册。' if exists else '邮箱可用'
        })


class RegisterView(generics.CreateAPIView):
    """用户注册视图"""
    permission_classes = [permissions.AllowAny]
    serializer_class = UserRegisterSerializer


class LoginView(APIView):
    """用户登录视图"""
    permission_classes = [permissions.AllowAny]

    def post(self, request):
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data.get('username')
            email = serializer.validated_data.get('email')
            phone = serializer.validated_data.get('phone')
            password = serializer.validated_data.get('password')
            
            # 根据提供的字段查找用户
            if username:
                user = authenticate(username=username, password=password)
            elif email:
                try:
                    user_obj = User.objects.get(email=email)
                    user = authenticate(username=user_obj.username, password=password)
                except User.DoesNotExist:
                    user = None
            elif phone:
                try:
                    user_obj = User.objects.get(phone=phone)
                    user = authenticate(username=user_obj.username, password=password)
                except User.DoesNotExist:
                    user = None
            else:
                user = None
            
            if user:
                # 更新最后登录时间
                user.last_login = timezone.now()
                user.save()
                
                # 记录登录日志
                LoginLog.objects.create(
                    user=user,
                    ip_address=self.get_client_ip(request),
                    is_success=True,
                    user_agent=request.META.get('HTTP_USER_AGENT', '')
                )
                
                # 生成JWT令牌
                refresh = RefreshToken.for_user(user)
                
                return Response({
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                    'user': UserSerializer(user).data
                })
            
            # 记录失败的登录尝试
            if username or email or phone:
                try:
                    if username:
                        user_obj = User.objects.get(username=username)
                    elif email:
                        user_obj = User.objects.get(email=email)
                    else:
                        user_obj = User.objects.get(phone=phone)
                    
                    LoginLog.objects.create(
                        user=user_obj,
                        ip_address=self.get_client_ip(request),
                        is_success=False,
                        user_agent=request.META.get('HTTP_USER_AGENT', '')
                    )
                except User.DoesNotExist:
                    pass
            
            return Response({"detail": "无效的凭据"}, status=status.HTTP_401_UNAUTHORIZED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip


class UserProfileView(generics.RetrieveUpdateAPIView):
    """用户个人资料视图"""
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_object(self):
        return self.request.user


class ChangePasswordView(generics.UpdateAPIView):
    """修改密码视图"""
    serializer_class = ChangePasswordSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = request.user
            # 检查旧密码
            if not user.check_password(serializer.validated_data['old_password']):
                return Response({"old_password": ["旧密码不正确"]}, status=status.HTTP_400_BAD_REQUEST)
            
            # 设置新密码
            user.set_password(serializer.validated_data['new_password'])
            user.save()
            return Response({"detail": "密码已成功修改"}, status=status.HTTP_200_OK)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class MembershipTypeListView(generics.ListAPIView):
    """会员类型列表视图"""
    queryset = MembershipType.objects.filter(is_active=True)
    serializer_class = MembershipTypeSerializer
    permission_classes = [permissions.AllowAny]


class UserLoginHistoryView(generics.ListAPIView):
    """用户登录历史视图"""
    serializer_class = LoginLogSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return LoginLog.objects.filter(user=self.request.user).order_by('-login_time')
